--[[
simple utils function
no state
--]]


local struct = require('struct')

local _M = {}

function table.val_to_str(v)
  if "string" == type(v) then
    v = string.gsub(v, "\n", "\\n")
    if string.match(string.gsub(v, "[^'\"]", ""), '^"+$') then
      return "'" .. v .. "'"
    end
    return '"' .. string.gsub(v, '"', '\\"') .. '"'
  else
    return "table" == type(v) and table.tostring(v) or
      tostring(v)
  end
end

function table.key_to_str(k)
  if "string" == type(k) and string.match(k, "^[_%a][_%a%d]*$") then
    return k
  else
    return "[" .. table.val_to_str(k) .. "]"
  end
end

function table.tostring(tbl)
  local result, done = {}, {}
  for k, v in ipairs(tbl) do
    table.insert(result, table.val_to_str(v))
    done[k] = true
  end
  for k, v in pairs(tbl) do
    if not done[k] then
      table.insert(result,
        table.key_to_str(k) .. "=" .. table.val_to_str(v))
    end
  end
  return "{" .. table.concat(result, ",") .. "}"
end

-- write to ./bin.dat
function _M.writeFile(binData)
  if not binData then
    print("nil binData")
    return
  end

  local f = assert(io.open("./bin.dat", "wb"))
  f:write(binData)
end

-- toString
function printObj(obj)
  str = ''
  if type(obj) == 'table' then
    for k, v in pairs(obj) do
      str = str .. ('k=' .. k .. ',v=' .. printObj(v))
    end
  else
    str = str .. obj
  end
  return str
end

function _M.printTbl(tbl)
  for k, v in pairs(tbl) do
    local tmpV
    if type(v) == 'table' then
      tmpV = 'table'
    else
      tmpV = '' .. v
    end
    print('k=' .. k .. ',v=' .. tmpV)
  end
end


function _M.makeBuffer(length, byte)
  local str = string.char(byte or 0x00)
  local tbl = {}
  for i = 1, length do
    table.insert(tbl, str)
  end
  return table.concat(tbl)
end


-- 解析dubbo

local hex_to_char = function(x)
  return string.char(tonumber(x, 16))
end

local unescape = function(url)
  return url:gsub("%%(%x%x)", hex_to_char)
end

function parseDubboRest(dubboStr)
  --  assert(type(dubboStr) == 'string', 'dubboStr not string')
  local url = unescape(dubboStr)
  local ip_port, stype, service = string.match(url, 'rest://(.-:.-)/(.-)/(.-)?.*')
  if not ip_port then return nil end
  return { ip_port = ip_port, stype = stype, service = service }
end

_M.printObj = printObj
_M.parseDubboRest = parseDubboRest

return _M
